<template>
  <div class="dept-lists">
    <el-card class="!border-none mt-4" shadow="never">
      <view class="card-warp">
        <el-form>
          <el-form-item label="套餐日期">
            <el-date-picker
              v-model="paramDay.day"
              type="date"
              :clearable="false"
              placeholder="选择套餐日期"
              format="YYYY-MM-DD"
              @change="resetParams"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
        <view class="searh-wrap mb-4">
          <text class="total-wrap">总销售量：{{ totalNum }}</text>
          <view v-show="showBtn">
            <el-button type="primary" @click="handleAddPackge()">
              <template #icon>
                <icon name="el-icon-Plus" />
              </template>
              新增
            </el-button>
            <el-button
              type="primary"
              :disabled="subDisabled"
              @click="onSubmit()"
            >
              保存
            </el-button>
            <el-button
              type="primary"
              :disabled="subDisabled"
              @click="orderMenuSetValidFun()"
            >
              生效
            </el-button>
          </view>
        </view>
      </view>
      <el-table
        size="large"
        v-loading="loading"
        :data="lists.filter((list) => list.isDelete !== 1)"
      >
        <el-table-column label="套餐编号" prop="mealSn" min-width="120" />
        <el-table-column label="套餐名称" prop="mealName" min-width="100" />
        <el-table-column label="套餐图片" prop="mealPic" min-width="100">
          <template #default="{ row }">
            <image-contain
              v-if="row.mealPic"
              :src="row.mealPic"
              :width="60"
              :height="45"
              :preview-src-list="[row.mealPic]"
              preview-teleported
              fit="contain"
            />
          </template>
        </el-table-column>
        <el-table-column label="配菜描述" prop="mealDescribe" min-width="120" />
        <el-table-column label="套餐原价" prop="price" min-width="100" />
        <el-table-column
          label="优惠价格"
          prop="preferentialAmount"
          min-width="100"
        />
        <el-table-column label="实际价格" prop="actualAmount" min-width="100" />
        <el-table-column label="本次销售数据" prop="salesNum" min-width="120" />
        <el-table-column label="库存" prop="stock" min-width="100" />
        <el-table-column label="操作" width="160" fixed="right" v-if="showBtn">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" link @click="handleStatus(row)">
              {{ row.status ? "下架" : "上架" }}
            </el-button>
            <el-button
              v-if="row.pid !== 0"
              type="danger"
              link
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <edit-popup
      v-if="showEdit"
      ref="editRef"
      @success="editSuccess"
      @close="showEdit = false"
    />
    <menus-popup ref="menusRef" @success="setLists" @close="showEdit = false" />
  </div>
</template>
<script lang="ts" setup name="department">
import type { ElTable } from "element-plus";
import EditPopup from "./edit.vue";
import MenusPopup from "./setMenus.vue";
import {
  getOrderMenuList,
  submitOrderMenu,
  orderMenuSetValid,
  orderMenuGetValid,
} from "@/api/admin/index";
import feedback from "@/utils/feedback";
import { timeFormat } from "@/utils/util";

const editRef = shallowRef<InstanceType<typeof EditPopup>>();
const menusRef = shallowRef<InstanceType<typeof MenusPopup>>();
const loading = ref(false);
const totalNum = ref(0);
const showBtn = ref(true);
const subDisabled = ref(true);
const validMenu = ref<any>({});
const lists = ref<any[]>([]);
const paramDay = reactive({
  day: null,
});
const showEdit = ref(false);

onMounted(async () => {
  orderMenuGetValid().then((res) => {
    validMenu.value = res;
    paramDay.day = new Date(res.day);
    resetParams(paramDay.day);
  });
});
const getLists = async (params: any = {}) => {
  loading.value = true;
  const res: any = await getOrderMenuList({
    day: params.day || timeFormat(paramDay.day),
  });
  let total_num = 0;
  lists.value = res.lists.map((item: any) => {
    total_num += item.salesNum;
    return item;
  });
  totalNum.value = total_num;
  loading.value = false;
  setDisabled(res.lists);
};

const setLists = (data: any) => {
  const listData: any[] = [];
  data.forEach((_data: any) => {
    let isPresence = false;
    lists.value.forEach((list: any) => {
      // 在原数据存在则存之前的数据
      if (_data.sn === list.mealSn) {
        list.isDelete = 0;
        listData.push(list);
        isPresence = true;
      }
    });
    _data.mealSn = _data.sn;
    _data.isDelete = 0;
    delete _data.sn;
    !isPresence && listData.push(_data);
  });
  lists.value = listData;
  subDisabled.value = true;
};

const resetParams = (val: any) => {
  const newDate = val.setHours(0, 0, 0, 0);
  const today = new Date().setHours(0, 0, 0, 0);
  // 判断是否之前的日期
  showBtn.value = today <= newDate;
  subDisabled.value = true;
  getLists({ day: timeFormat(val) });
};

const editSuccess = (formData: any) => {
  lists.value = lists.value.map((list: any) => {
    if (list.id === formData.id) {
      list = {
        ...list,
        ...formData,
        actualAmount: parseFloat(
          (formData.price - formData.preferentialAmount).toFixed(2)
        ),
      };
    }
    return list;
  });
  setDisabled(lists.value);
};

const setDisabled = (listData: any) => {
  let _disabled = !listData.length;
  for (const list of listData) {
    if (
      typeof list.price !== "number" ||
      typeof list.preferentialAmount !== "number" ||
      typeof list.stock !== "number"
    ) {
      _disabled = true;
      break;
    }
  }
  subDisabled.value = _disabled;
  return _disabled;
};

const onSubmit = async () => {
  const day: string = timeFormat(paramDay.day);
  const params = {
    day,
    mealList: lists.value.map(
      ({ mealId, price, preferentialAmount, stock, seq, status }: any) => ({
        mealId,
        price,
        preferentialAmount,
        stock,
        status,
        seq,
      })
    ),
  };
  submitOrderMenu(params)
    .then((res) => {
      feedback.msgSuccess("保存成功");
      getLists();
    })
    .catch(() => {
      feedback.msgError("保存失败，请重试！");
    });
};

const handleEdit = async (data: any) => {
  showEdit.value = true;
  await nextTick();
  editRef.value?.open("edit");
  editRef.value?.setFormData(data);
};

const handleStatus = (row: any) => {
  row.status = row.status ? 0 : 1;
};

const handleAddPackge = async () => {
  await nextTick();
  const _day: any = timeFormat(paramDay.day);
  const mealSns = lists.value.map(({ mealSn }) => mealSn);
  menusRef.value?.open(_day);
  menusRef.value?.getLists(mealSns);
};

const handleDelete = async (row_id: number) => {
  await feedback.confirm("确定要删除？");
  lists.value = lists.value.filter(({ id }: any) => row_id !== id);
  setDisabled(lists.value);
};

const orderMenuSetValidFun = () => {
  let isSubmit = true;
  let id = -1;
  lists.value.forEach(({ menuId }) => {
    !menuId ? (isSubmit = false) : (id = menuId);
  });
  if (isSubmit) {
    orderMenuSetValid({ id })
      .then(() => {
        feedback.msgSuccess("设置成功");
      })
      .catch(() => feedback.msgError("设置失败，请重试！"));
  } else {
    feedback.msgError("请先提交后设置生效");
  }
};
</script>
<style scoped lang="scss">
.card-warp,
.searh-wrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .total-wrap {
    margin-right: 100px;
    white-space: nowrap;
    flex: 1;
  }
}
</style>
